import React from 'react';
import ReactDOM from 'react-dom';
import { inject, observer } from 'mobx-react';
import { withRouter } from 'react-router-dom';
import { Comment, Reply } from 'weaver-mobile-page';
import { Tools } from 'weaver-mobile';
import { toJS, autorun } from 'mobx';
import WrAlertPage from '../../../../public/alertPage'
import * as Util from "../../../../util";
import dict from '../../../../util/wea-workrelate-file';
const getLabel = Tools.getLabel;
dict.addWindowFunc();

@inject('taskCommentStore')
@withRouter
@observer
class CommentInfo extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      ...props
    }
    this.replyRef = React.createRef();
  }

  componentWillMount() {
    let { setTaskId, changeTaskDetail, changeCategory, changeAllCommentList } = this.props.taskCommentStore
    let { taskid, detail } = this.state
    setTaskId(taskid)
    changeTaskDetail(detail)
    changeAllCommentList([])

    Tools.callApi({
      url: "/api/workrelate/task/getTaskFileCategory",
      method: "GET",
      params: {},
      type: "json"
    }).then((data) => {
      if (data.status == 1) {
        changeCategory(data.secId)
      }
    })
  }

  componentWillReceiveProps(newProps) {
    let { taskDetail, changeTaskDetail, commentStore, changeCommentList, changeReplyid } = this.props.taskCommentStore
    let taskOldStatus = taskDetail.taskstatus
    let taskNewStatus = newProps.detail.taskstatus
    changeTaskDetail(newProps.detail)
    if (taskOldStatus != taskNewStatus && taskNewStatus == "2") {
      changeCommentList([])
      changeReplyid("")
      commentStore.getDatas()
    }
  }


  componentWillUpdate() {
    let { replyFocus } = this.props.taskCommentStore;
    if (replyFocus) {
      this.setReplyVisible(replyFocus)
    }
  }

  componentDidMount() {
    const { autoFocus } = this.state
    if (autoFocus == "1") {
      // this.setReplyVisible(true)
    }
  }

  componentWillUnmount() {
    const { changeCommentList } = this.props.taskCommentStore
    changeCommentList([])
  }

  /**
   * 设置回复是否获取焦点
   */
  setReplyVisible = (val) => {
    const replyRef = this.replyRef;
    if (replyRef) {
      replyRef.setState({ visible: val }, () => {
        replyRef.getInputFocus();
      });
    } else {
      window.setTimeout(() => {
        this.setReplyVisible();
      }, 0)
    }
  }

  /**
   * 提交反馈信息
   */
  submitReply = (data) => {
    let { addTaskFeedBack, replyid, mainId, toUserId, changeReplyAttachDatas, sending } = this.props.taskCommentStore
    let { taskid } = this.state
    let content = this.transContent(data)
    let params = { taskId: taskid, content, replyid }
    if (content.replace(new RegExp(/<\/?[a-z]+>/img), "") && !sending) {
      addTaskFeedBack(params)
    }
    this.replyRef && this.replyRef.replyRef.setVisible(false)
    changeReplyAttachDatas({})
    this.setSendIconStyle("0")
  }


  //name = '', ids = '', list = [], type = '',relateId='',model=''
  /**
   * 转换内容
   */
  transContent = (data) => {
    let { taskid } = this.state;
    let str = data.text;
    if (data.attach.doc && data.attach.doc.length > 0) {
      str += Util.transfStr("Browser", "", data.attach.doc, 37, taskid, 2);
    }
    if (data.attach.flow && data.attach.flow.length > 0) {
      str += Util.transfStr("Browser", "", data.attach.flow, 152, taskid, 2);
    }
    if (data.attach.customer && data.attach.customer.length > 0) {
      str += Util.transfStr("Browser", "", data.attach.customer, 7, taskid, 2);
    }
    if (data.attach.project && data.attach.project.length > 0) {
      str += Util.transfStr("Browser", "", data.attach.project, 8, taskid, 2);
    }
    if (data.attach.file && data.attach.file.length > 0) {
      str += Util.transfStr("Upload", "", data.attach.file, "file", taskid, 2);
    }
    return str;
  }

  onFocusBulr = () => {
    let { taskCommentStore } = this.props;
    if (taskCommentStore.replyFocus) {
      taskCommentStore.replyFocus = false;
    }
  }

  onAttachDatasChange = (key, datas) => {
    const { replyAttachDatas, changeReplyAttachDatas } = this.props.taskCommentStore

    replyAttachDatas[key] = datas || []

    let canSend = false
    for (let k in replyAttachDatas) {
      if (replyAttachDatas[k] && replyAttachDatas[k].length > 0) {
        canSend = true
      }
    }

    this.setSendIconStyle(canSend ? "1" : "0")
  }

  setSendIconStyle = (type) => {
    let sendIcon = document.querySelector(".workrelate-mobile-task-commentinfo-wrapper svg.am-icon-send")
    if (sendIcon) {
      if (type == "0") {    // 置灰
        sendIcon.classList.remove("wm-reply-input-icon-active")
        sendIcon.classList.add("wm-reply-input-icon-base")
      } else if (type == "1") {   // 高亮
        sendIcon.classList.remove("wm-reply-input-icon-base")
        sendIcon.classList.add("wm-reply-input-icon-active")
      }
    }
  }

  render() {
    const { replyStore, commentStore, commentList, replyFocus } = this.props.taskCommentStore
    const leftConfig = [
      // { type: 'voice' },
      // { type: 'blog-biaoqing' },
      // { type: 'blog-tupian' },
      // { type: '@' },
      { type: 'tianjia' },
    ];
    // const rightConfig = { type: 'private', text: '私密' };
    return (
      <div className="workrelate-mobile-task-commentinfo-wrapper">
        <div className="content-wrapper">
          <div className="comment-wrapper">
            <Comment
              store={commentStore}
              outClassName="hide-comment-more-child-reply"
            />
          </div>
        </div>
        <div className="foot-wrapper">
          <Reply
            wrappedComponentRef={ref => this.replyRef = ref} // 由于react升级，ref={ref => this.replyRef = ref} 这种方式不能用了，这里取ref请按照目前给的这个方式
            store={replyStore}
            leftConfig={leftConfig}
            // rightConfig={rightConfig} // 右侧配置（不需要可以不设置）
            showOutInput
            onSubmitButtonClick={datas => this.submitReply(toJS(datas))} // 提交的时候，如果需要清空数据，调用store的doClear方法
            onFocus={() => this.onFocusBulr()}
            onBlur={() => this.onFocusBulr()}
            onBrowserChange={(key, datas) => {
              this.onAttachDatasChange(key, datas)
            }}
            onUploadChange={(key, datas) => {
              this.onAttachDatasChange(key, datas)
            }}
          />
        </div>
      </div>
    )
  }

}
export default CommentInfo